using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using System.Threading;
using System.Globalization;
using System.Xml;

namespace AutoUpdate
{
    static class Program
    {
        /// the program that called the auto update
        public static String ExeFile = null;
        /// the web location of the files
        public static String RemoteUri = null;
        /// the key used by the program when called back 
        public static String ManifestFile = null; 
        /// procesul care se va oprii;
        public static String StopProcessName = null;
        /// <summary>
        /// serverul proxy
        /// </summary>
        public static String ProxyServer = null;
        /// <summary>
        /// portul proxy
        /// </summary>
        public static int ProxyPort = 0;
        public static Boolean FinalizareAutomata = true;
        public static int DBVersion = 0;
        
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        /// 
        [STAThread]
        static void Main()
        {

            #region schimbare director curent
            //lanseaza aplicatia din calea in care este instlata
            FileInfo fi = new FileInfo(Application.ExecutablePath);
            Directory.SetCurrentDirectory(fi.Directory.FullName);
            
            #endregion
            Application.EnableVisualStyles();            
            Application.SetCompatibleTextRenderingDefault(false);
            Configuration config = null,conCre=null;
            try
            {
                // Get the application configuration file.OpenExeConfiguration*/
               config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
            }
            catch (ConfigurationErrorsException)
            {
                
                conCre = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                if (conCre != null)
                    conCre.SaveAs("ERPStudio.exe.config");
                //trebuie sa existe si fisierul .exe
                FileStream sw = File.Create("ERPStudio.exe");
                if(sw!=null)
                    sw.Close();
                config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
                // nu mai e nevoie de ele aducem altul...
                File.Delete("ERPStudio.exe");
            }

            try
            {
                if (config == null || config.AppSettings == null || config.AppSettings.Settings==null)
                {
                    MessageBox.Show("Fisierul de configurare pt. AutoUpdate nu are sectiunea setari aplicatie!");
                    return ;
                }

                KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;
                Boolean salvare = false;
                if (configSettings["RemoteURL"] == null)
                {
                    configSettings.Add(new KeyValueConfigurationElement("RemoteURL", "http://www.datastudio.ro/Update/Demo/"));
                    salvare = true;
                    RemoteUri = "http://www.datastudio.ro/Update/Demo/";
                }
                else
                    RemoteUri = configSettings["RemoteURL"].Value.ToString().Trim();
               

                if (configSettings["ManifestFile"] == null)
                {
                    configSettings.Add(new KeyValueConfigurationElement("ManifestFile", "ERP.xml"));
                    salvare = true;
                    ManifestFile = "ERP.xml";
                }
                else
                    ManifestFile = configSettings["ManifestFile"].Value.ToString().Trim();


                if (configSettings["StopProcessName"] == null)
                {
                    configSettings.Add(new KeyValueConfigurationElement("StopProcessName", "ERPStudio.exe"));
                    salvare = true;
                    StopProcessName = "ERPStudio.exe";
                }
                else
                    StopProcessName = configSettings["StopProcessName"].Value.ToString().Trim();

                if (configSettings["ProxyServer"] == null)
                {
                    configSettings.Add(new KeyValueConfigurationElement("ProxyServer", ""));
                    salvare = true;
                    ProxyServer = String.Empty;
                }
                else
                    ProxyServer = configSettings["ProxyServer"].Value.ToString().Trim();

                if (configSettings["ProxyPort"] == null)
                {
                    configSettings.Add(new KeyValueConfigurationElement("ProxyPort", ""));
                    salvare = true;
                    ProxyPort = 0;
                }
                else
                    if (configSettings["ProxyPort"].Value.ToString().Trim()!=String.Empty)
                        ProxyPort = Convert.ToInt32(configSettings["ProxyPort"].Value.ToString());
                if (configSettings["FinalizareAutomata"] == null)
                {
                    configSettings.Add(new KeyValueConfigurationElement("FinalizareAutomata", "Da"));
                    salvare = true;
                    FinalizareAutomata = true;
                }
                else
                    if (configSettings["FinalizareAutomata"].Value.ToString().Trim() != String.Empty)
                        if (configSettings["FinalizareAutomata"].Value.ToString().Trim().ToLower() == "da")
                            FinalizareAutomata = true;
                        else
                            FinalizareAutomata = false;

                //versiunea bazei de date cu care lucreaza
                if (configSettings["DBVersion"] == null)
                {
                    ///daca nu exista adauga
                    ///
                    configSettings.Add(new KeyValueConfigurationElement("DBVersion", "0"));
                    salvare = true;
                    DBVersion = 0;
                }
                else
                    DBVersion = Convert.ToInt32(configSettings["DBVersion"].Value);

                // Save the configuration file.

                ConfigurationSection section = config.GetSection("connectionStrings");
                if (section == null)
                {
                    Trace.WriteLine("[" + DateTime.Now.ToString() + "] GetSection stringuri de conectare returnat null!");
                    Trace.Flush();
                    return;
                }

                if (section.SectionInformation.IsProtected)
                {
                    try
                    {
                        section.SectionInformation.UnprotectSection();
                        Trace.WriteLine("[" + DateTime.Now.ToString() + "] Deprotejare sectiune cripatata siruri de conectare!");
                    }
                    catch (Exception)
                    {
                        config.Sections.Remove("ConnectionStrings");
                        Trace.WriteLine("[" + DateTime.Now.ToString() + "] Eroare la deprotejare sectiune cripatata siruri de conectare!");
                    }
                }

                if (config.ConnectionStrings.ConnectionStrings.Count == 0
                    || ((config.ConnectionStrings.ConnectionStrings.Count == 1) && (config.ConnectionStrings.ConnectionStrings[0].Name == "LocalSqlServer")))
                {
                    salvare = true;
                    //nu exista nici un connection string
                    String cfgString = @"Data Source=.\SQLEXPRESS;Initial Catalog = ESRP; User ID=Admin;Password=Password2009;Net=dbmslpcn;Connection Timeout=15;";
                    config.ConnectionStrings.ConnectionStrings.Add(
                        new ConnectionStringSettings("AdminConnectionString", cfgString));
                    config.ConnectionStrings.ConnectionStrings.Add(
                        new ConnectionStringSettings("ESRPConnectionString", cfgString));
                    config.ConnectionStrings.ConnectionStrings.Add(
                        new ConnectionStringSettings("PersSalConnectionString", cfgString));
                    config.ConnectionStrings.ConnectionStrings.Add(
                        new ConnectionStringSettings("ERPConnectionString", cfgString));
                    config.ConnectionStrings.ConnectionStrings.Add(
                        new ConnectionStringSettings("SANConnectionString", cfgString));
                    config.ConnectionStrings.ConnectionStrings.Add(
                        new ConnectionStringSettings("SallyConnectionString", cfgString));
                }

                if (salvare)
                    config.Save(ConfigurationSaveMode.Full);

            }
            catch (ConfigurationErrorsException err)
            {
                MessageBox.Show("Eroare configurare: " + err.ToString());
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Eroare la Salvare : " + ex.Message);
            }

            if (ExeFile == String.Empty || RemoteUri == String.Empty 
                || ManifestFile == String.Empty || StopProcessName == String.Empty) 
                Environment.Exit(1);

            FrmAutoUpdate myForm = new FrmAutoUpdate(StopProcessName, ProxyServer, ProxyPort, FinalizareAutomata, config);
            myForm.Label1.Text = "Verificare actualizari aplicatie, va rugam asteptati...";
            if (StopProcessName!= "-")
                myForm.KillAppExe(StopProcessName);

            Stream myFile = null;
            while (myFile == null)
            {
                try
                {
                    myFile = File.OpenWrite(Directory.GetCurrentDirectory() + "\\Trace.log");
                }
                catch 
                { 
                    
                }
            }
            //mergem la sfarsit
            
           
            myFile.Position = myFile.Length; 
            TextWriterTraceListener myTextListener = new TextWriterTraceListener(myFile);
            Trace.Listeners.Add(myTextListener);

            // Write output to the file.
            Trace.WriteLine(DateTime.Now.ToString() + " Start Update: " + DateTime.Now.ToString());
            Trace.Flush(); 

            Trace.WriteLine(DateTime.Now.ToString() + "| Inainte de Application.Run(myForm);");
            Trace.Flush();
            try
            {
                Application.Run(myForm);
            }
            catch(Exception ex)
            {
                Trace.WriteLine(DateTime.Now.ToString() + "| " + ex.ToString());
                Trace.Flush();
                MessageBox.Show("Functionare anormala!\nVa rugam trimiteti fisierul trace.log din catalogul aplicatiei pe adresa: info@datastudio.ro!", "avertisment", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            Trace.Flush();
            //inchide fisierul de trace inainte de apelarea procesului
            Trace.Close();
            if (StopProcessName != "-")
                myForm.Start(StopProcessName);
        }
    }
}